#include "../include/tool.h"
#include "../include/memory/memory_pool.h"

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

extern MemoryPool g_mem_pool;

MemoryCell *Tool::malloc(uint size)
{
    return g_mem_pool.new_chunk(size, __FILE__, __LINE__)->malloc_fast(size);
}

pvoid Tool::malloc_fast(uint size)
{
    return g_mem_pool.new_chunk(size, __FILE__, __LINE__)->malloc_fast(size)->ptr();
}

//=====
string &Tool::replace_all(string &str, string old_value, string new_value)
{
    while(true) {
        string::size_type pos(0);

        if((pos = str.find(old_value)) != string::npos) {
            str.replace(pos, old_value.length(), new_value);
        } else {
            break;
        }
    }

    return str;
}

string Tool::generate_jni_function_name(string class_name, string method_name)
{
    string new_class_name = replace_all(class_name, "/", "_");

    return "Java_" + new_class_name + "_" + method_name;
}

JavaClassContent *Tool::readfile(string filepath)
{
    FILE* file = NULL;
    uint filesize = 0;
    char *content = NULL;

    JavaClassContent * class_content= new JavaClassContent;
    class_content->set_filepath(filepath);
    class_content->set_pointer(0);

    /* 打开class文件 */
    if (NULL == (file = fopen(filepath.c_str(), "rb"))) {
        perror("fopen fail");

        exit(1);
    }

    /* 获取class文件字节数 */
    if (0 != fseek(file, 0, SEEK_END)) {
        perror("fseek fail");

        exit(1);
    }

    filesize = (int)ftell(file);
    if (-1 == filesize) {
        perror("ftell fail");

        exit(1);
    }

    class_content->set_filesize(filesize);

    /* 将文件内容读入内存 */
    fseek(file, 0, SEEK_SET);

    class_content->set_content(malloc(filesize * sizeof(char)));

    if (NULL == (content = (char *)class_content->get_content()->ptr())) {
        ERROR_PRINT("分配内存失败\n");

        exit(1);
    }

    fread(content, sizeof(char), filesize, file);

    fclose(file);

    return class_content;
}